package com.mall.commons.exception;

import com.mall.commons.common.CommonResult;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author Pan Rundong
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 重复异常
     * @Author: Pan Rundong
     * @Date: 2023-02-09 14:32
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param ex
     * @return com.itheima.youdianda.common.R<java.lang.String>
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public CommonResult<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());
        String exceptionName = "Duplicate entry";

        if(ex.getMessage().contains(exceptionName)){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return CommonResult.error(msg);
        }

        return CommonResult.error("未知错误");
    }

    /**
     * 返回业务异常
     * @Author: Pan Rundong
     * @Date: 2023-02-09 14:35
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param ex
     * @return com.itheima.youdianda.common.R<java.lang.String>
     */
    @ExceptionHandler(CustomException.class)
    public CommonResult<String> exceptionHandler(CustomException ex){
        log.info(ex.getMessage());

        return CommonResult.error(ex.getMessage());
    }

    /**
     * token不合法异常
     * @Author: Pan Rundong
     * @Date: 2023-02-10 19:03
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param ex
     * @return com.itheima.youdianda.common.R<java.lang.String>
     */
    @ExceptionHandler(SignatureException.class)
    public CommonResult<String> exceptionHandler(SignatureException ex) {
        log.info(ex.getMessage());
        return CommonResult.error("token不合法");
    }

    /**
     * token过期异常
     * @Author: Pan Rundong
     * @Date: 2023-02-10 19:04
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param ex
     * @return com.itheima.youdianda.common.R<java.lang.String>
     */
    @ExceptionHandler(ExpiredJwtException.class)
    public CommonResult<String> exceptionHandler(ExpiredJwtException ex) {
        log.info(ex.getMessage());
        return CommonResult.error("token已过期");
    }
}
